export default {
	data() {
		return {
			getToken: '',
			btnSwitch: true, //提交按钮防止重复提交
			showImg: '', //是否显示图片
			nameType: '', //显示全称或简称
			templatetype: '', //模版选择
			sideIdent: 0, //侧边导航是否选中标识
			goodsPageIndex: 1, //商品页数
			goodsList: [], //商品信息
			categoryList: [], //一级分类
			TwoCategoryList: [], //二级分类
			category_id: '',
			status: 'loading', //加载状态
			isEmpty: false, //是否显示空页面
			searchText: '', //搜索关键词
			goodsSearchText: '',
			
			orderType: '', //排序方式
			conditionIdent: 0, //筛选标识
			priceIdent: 0, //价格标识
			categoryTwoIdent: 0,
			ident: false, //防止初始化时，触发上拉加载
			sideClickIndex: -1, //防止重复侧导航栏重复点击
			searchIndex: true,
			priceIndex: true,
			pageCount: 0,
			Scroll:"",
			token:"",
			maskLayerOpen: false, //防止页面穿透
			goodsDetail:{},
			currentGoodsSkuName: [], //当前选中的规格名称集合
			isIphoneX: false, //判断手机是否是iphoneX以上
			number: 1, //购买数量
			selectedSkuInfo: {
				picCoverSmall: "", //预览图
				stock: 0,
				displayPrice: 0,
			},
			goodsId: 0,
			skuId: 0,
			groupId: 0,
			bargainId: 0,
			skuList:[]
			
		};
	},
	mouted() {
		console.log("mouted===============")
		 window.onbeforeunload = e => {      //刷新时弹出提示
		        cosole.log("00000000000000")
		    };

	},

	// onPageScroll(e) {
	// 	console.log("e==================",e)
	// 	this.Scroll=e.scrollTop
	// 	// uni.setStorageSync('scrollTopIndex', this.Scroll)
	// },
	created() {
		
		console.log("created===============")
	},
	onLoad() {
		this.getXufei();
		console.log("onLoad================",uni.getStorageSync('id'))
		this.getCategoryType();
		this.getCategoryInfo();
		console.log("asdasdasdasd222222222")
		// console.log('999999999',uni.getStorageSync('id'))
		// this.sideClickIndex=uni.getStorageSync('id')
		
		// console.log('66666',this.sideClickIndex)
		
	},
	onShow(){
		this.getToken = uni.getStorageSync('token')
		uni.getSystemInfo({
			success: res => {
				if (res.model.search('iPhone X') != -1) {
					this.isIphoneX = true;
				}
			}
		});
		this.token = uni.getStorageSync('token');
		
console.log("onShow================")
		
		if(uni.getStorageSync('sideIdentId')){
			this.sideIdentId=uni.getStorageSync('sideIdentId')
		}
		
		if(uni.getStorageSync('categoryId')){
			this.category_id=uni.getStorageSync('categoryId')
			
			
		}
		
		if(uni.getStorageSync('id')){
			this.getCategoryInfo()
		}
		
		
		
	
	},
	onHide(){
		uni.removeStorageSync('id')
		console.log('删除============',uni.getStorageSync('id'))
	},
	onUnload(){
		
		console.log("onUnload======================")
	},
	methods: {
		closeSkuPopup() {
			this.$refs.skuPopup.close();
		},
		changeNum(tag) {
			if (this.selectedSkuInfo.stock == 0) return;
		
			if (tag == '+') {
				if(this.number >= 0 ){
					this.number = this.number + this.goodsDetail.min_buy;
				}else{
					uni.showToast({
						title:'当前数量不合法'
					})
				}
				
				// 加
				// if (this.number < this.maxBuy) {
				// 	// this.number++
				// 	this.number = this.number + this.goodsDetail.min_buy;
				// } else {
				// 	return;
				// }
			} else if (tag == '-') {
				if (this.number <= 0 ){
					uni.showToast({
						title:'无法减少'
					})
				}
				else{
					this.number = this.number - this.goodsDetail.min_buy
				}
				// 减
				// if ((this.number > this.minBuy && this.minBuy > 0) || (this.number > 1 && this.minBuy == 0)) {
				// 	this.number = this.number - this.goodsDetail.min_buy
				// } else {
				// 	return;
				// }
			}
		
		},
		confirm() {
			
			if(this.number <= 0){
				uni.showToast({
					title:'当前购买数量不合法'
				})
			}else{
				if (this.token != '') {
				
					//纠正数量
					//this.keyInput();
					// this.number = this.number.replace(/[^\d]/g,"")
					this.number = parseInt(this.number)
					console.log('this.number==========',this.number)
					if (isNaN(this.number)) this.number = this.minBuy;
					if (this.selectedSkuInfo.stock == 0) {
						this.$util.showToast({
							title: '商品已售罄',
						});
						return;
					}
					if (this.btnSwitch == false) {
						return;
					}
					this.btnSwitch = false;
					
						
				
						var cart_detail = {
							goods_id: this.goodsId,
							count: this.number,
							goods_name: this.goodsDetail.goods_name,
							sku_id: this.skuId,
							sku_name: this.selectedSkuInfo.sku_name,
							price: this.selectedSkuInfo.price,
							picture_id: this.pictureId,
							shop_name: ''
						};
				
						this.sendRequest({
							url: "System.Goods.addCart",
							data: {
								"cart_detail": JSON.stringify(cart_detail)
							},
							success: res => {
								console.log("res========================",res)
								var data = res.data;
								console.log("data-------------------------",data)
								this.$refs.skuPopup.close();
								if (data.code > 0) {
									this.$util.showToast({
										title: '加入购物车成功',
									});
									// this.getCartCount();
								} else if (data.code == -1) {
									this.$util.showToast({
										title: '只有会员登录之后才能购买，请进入会员中心注册或登录。',
									});
								} else if (data.code == 0) {
									this.$util.showToast({
										title: data.message,
									});
								}else if (res.code == -99999){
									console.log("sssssssssssssssssssssssssssssss")
									this.$util.showToast({
										title: res.message,
									});
								}
								this.btnSwitch = true;
							}
				
				
						});
				
				} else {
					console.log("+++++++++++++++++",this.$refs)
					this.$refs.login.clickLogin();
				
				}
			}
			
		},
		// getCartCount() {
		// 	this.sendRequest({
		// 		url: "System.Goods.cartCount",
		// 		data: {},
		// 		success: res => {
		// 			if (this.leftOperation.length > 1) {
		// 				this.leftOperation[2].info = res.data;
		// 			}
		// 		}
		// 	});
		// },
		addshopping(e){
			console.log("************************",e)
			this.goodsId=e.goods_id
			this.skuId=e.sku_list[0].sku_id
			this.getGoodsDetail()
			//同步获取商品详情
			this.maskLayerOpen = true;
			this.$refs.skuPopup.open(() => {
				console.log("656666666666")
				this.maskLayerOpen = false;
			});
		},
		async getGoodsDetail() {
			let res = await this.sendRequest({
				url: 'System.Goods.goodsDetail',
				async: false,
				data: {
					goods_id: this.goodsId,
					sku_id: this.skuId,
					group_id: this.groupId,
					bargain_id: this.bargainId
				}
			});
			let data = res.data;
			console.log("data==================",data)
			if (data != null && data.goods_detail) {
				this.goodsDetail = data.goods_detail;
				this.skuList = this.goodsDetail.sku_list;
				this.refreshSku();
				console.log("ssssssssssssssssssssssssssss",this.goodsDetail)
				
			} else {
				
				uni.showToast({
					title:"商品信息有误",
					icon:'none'
				})
			}
		},
		scroll: function(Object) {
		 console.log(Object.detail);//实时获取到滚动的值
		},
		refreshSku() {
		
			//匹配当前选中的商品规格，找到sku_id
			var sku_length = this.goodsDetail['spec_list'].length; //应选中规格数量
		
			this.pictureId = this.goodsDetail.picture;
			if (this.skuList.length > 1) {
		
				for (let i = 0; i < this.skuList.length; i++) {
					let item = this.skuList[i];
					let value = item.attr_value_items;
					let match_sku_count = 0; //匹配规格数量
					this.currentGoodsSkuName = []; //每次匹配时都要清空
		
					for (let j = 0; j < this.goodsDetail['spec_list'].length; j++) {
						let spec = this.goodsDetail['spec_list'][j];
						for (let k = 0; k < spec.value.length; k++) {
		
							if (spec.value[k].selected && !spec.value[k].disabled) {
								let index = value.indexOf(spec.value[k].spec_id + ":" + spec.value[k].spec_value_id);
								if (index > -1) {
									match_sku_count++;
									this.currentGoodsSkuName.push(spec.value[k].spec_name + ":" + spec.value[k].spec_value_name);
								}
							}
		
						}
					}
		
					if (sku_length == match_sku_count) {
		
						this.skuId = item.sku_id;
						this.selectedSkuInfo = item;
						break;
		
					}
		
				}
		
			} else {
				this.skuId = this.skuList[0].sku_id;
				this.selectedSkuInfo = this.skuList[0];
			}
		
			if (this.selectedSkuInfo.picture > 0) {
				this.pictureId = this.selectedSkuInfo.picture;
				this.selectedSkuInfo.picCoverSmall = this.selectedSkuInfo.sku_img_main.pic_cover_small;
			} else {
				this.selectedSkuInfo.picCoverSmall = this.goodsDetail['img_list'][0]['pic_cover_small'];
			}
		
			this.selectedSkuInfo.displayPrice = this.selectedSkuInfo.promote_price;
			if (this.token != '') {
		
				if (parseFloat(this.selectedSkuInfo.member_price) < parseFloat(this.selectedSkuInfo.promote_price)) {
					this.selectedSkuInfo.displayPrice = this.selectedSkuInfo.member_price;
				}
		
			}
		
			if (this.selectedSkuInfo.stock > 0) {
				this.maxBuy = this.goodsDetail.max_buy > 0 ? this.goodsDetail.max_buy : this.selectedSkuInfo.stock;
				this.minBuy = this.goodsDetail.min_buy > 0 ? this.goodsDetail.min_buy : 1;
			} else {
				this.maxBuy = 0;
				this.minBuy = 0;
			}
		
			// 预售、团购、、积分等活动不需要改变价格
			if ((this.topPermissions == 1) || (this.goodsDetail.point_exchange_type != 2 && this.goodsDetail.point_exchange_type !=
					3 && this.promotionType != 2 && this.orderType != 4 && this.orderType != 6 && this.promotionType != 7)) {
		
				if (this.promotionType == 3) {
					//砍价活动取原价
					this.selectedSkuInfo.displayPrice = this.selectedSkuInfo.price;
				}
		
				var pointText = "";
				if (this.goodsDetail.point_exchange_type == 1 && this.goodsDetail.point_exchange > 0) {
					pointText = "+" + this.goodsDetail.point_exchange + "积分";
				}
				this.selectedSkuInfo.displayPrice = "¥" + this.selectedSkuInfo.displayPrice + pointText;
			}
		
			// 如果是拼团活动
			if (this.orderType == 4 && this.goodsDetail['promotion_detail']['pintuan'] != null) {
		
				for (let i in this.goodsDetail['promotion_detail']['pintuan']['data']['sku_list']) {
					let curr = this.goodsDetail['promotion_detail']['pintuan']['data']['sku_list'][i];
					if (curr.sku_id == this.skuId) {
						this.selectedSkuInfo.displayPrice = "¥" + curr.tuangou_price;
					}
				}
			}
		
			this.number = this.minBuy;
		
		},
		
		getXufei(){
			
			this.sendRequest({
				url: 'System.Member.getCate',
				success: res => {
					if (res.data.code == -9999) {
						// 未登录
			
					} else if (res.code == 0) {
						// Date ddd = new Date();
						var newDay = parseInt(new Date().getTime() / 1000)
						//15552000  6个月前的时间戳(秒)
						if(res.data.order_info){
							if (parseInt(newDay - res.data.order_info.pay_time) > 15552000 || res.data.order_info.distribution_status == 1) {
								console.log("5555555555")
								uni.showModal({
									title: '提示',
									content: '你必须要续费才能正常使用',
									cancelText: "取消", // 取消按钮的文字  
									confirmText: "确定", // 确认按钮文字  
									showCancel: true, // 是否显示取消按钮，默认为 true
									success: (successRes) => {
										if (successRes.confirm) {
										uni.navigateTo({
											url:'/pages/index/index/pay?out_trade_no='+res.data.order_info.out_trade_no
										})
										} else {
											if (uni.getSystemInfoSync().platform == 'ios'){
											    plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
											} else if (uni.getSystemInfoSync().platform == 'android'){
											    plus.runtime.quit();
											}
										}
									}
								})
							}
						}
						
		
					}
			
				}
			});
		},
		/**
		 * 获取分类展示信息
		 */
		getCategoryType() {
			this.sendRequest({
				url: 'System.Goods.getAppletCategoryDisplay',
				success: res => {
					
					if(res.data.code == -99999){
					}else{
						this.showImg = res.data.is_img;
						this.nameType = res.data.is_use;
						this.templatetype = res.data.template;
					}
					
				}
			});
		},
		/**
		 * 获取分类信息
		 */
		getCategoryInfo() {
			
			console.log("哈哈哈哈哈哈==========================")
			this.sendRequest({
				url: 'System.Goods.goodsCategoryList',
				success: res => {
					if (res.data.length > 0) {
						/* 一级分类 */
						this.categoryList = res.data;
						
						console.log("categoryList=================",this.categoryList)
						if(uni.getStorageSync('id')){
							this.categoryList.forEach((item,index)=>{
								console.log("sssssssssssssssssssss",uni.getStorageSync('id'))
								console.log("2222222222222222222222",item.category_id)
								if( uni.getStorageSync('id')==item.category_id){
									this.sideIdent=index
									console.log("999999999999999999999",index)
								}
							})
						}
						
						
						if(!uni.getStorageSync('id')){
							
							
							console.log("sssssssssssssssssssssssssssss")
							
							this.category_id = uni.getStorageSync('categoryId')?uni.getStorageSync('categoryId'):this.categoryList[0].category_id
							
							uni.setStorageSync('categoryId',this.category_id)
							this.goodsPageIndex=1;
							this.goodsList = [];
							this.status='loading'
							this.getGoodsInfo();
						}else{
								console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaa")
							this.goodsPageIndex=1;
							this.goodsList = [];
							this.status='loading'
							this.category_id=uni.getStorageSync('id')
							console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaa",this.category_id)
							this.getGoodsInfo();
						}
						/* 二级分类 */
						this.TwoCategoryList = this.categoryList[0].child_list;
					} else {
						this.isEmpty = true;
					}
					if (this.$refs.loadingCover == undefined) return;
					this.$refs.loadingCover.hide();
				},
				fail: res => {
					if (this.$refs.loadingCover == undefined) return;
					this.$refs.loadingCover.hide();
				}
			});
		},
		godeng(){
			// pages/login/login/login
			uni.navigateTo({
				url:'/pages/login/login/login'
			})
		},
		/**
		 * 获取商品信息
		 */
		getGoodsInfo(type = '') {
			let condition = {};
			if (type == 'refresh') {
				this.goodsPageIndex = 1;
				this.goodsList = [];
				this.status = 'more';
			}
			if (this.status == 'nomore') return;
			if (this.goodsSearchText == '') {
				condition = JSON.stringify({
					'ng.category_id': this.category_id,
					'ng.state': 1
				});
			} else {
				condition = JSON.stringify({
					'ng.category_id': this.category_id,
					'ng.state': 1,
					'ng.goods_name': ['like', '%' + this.goodsSearchText + '%']
				});
			}
			this.sendRequest({
				url: 'System.Goods.goodsList',
				data: {
					page_index: this.goodsPageIndex,
					page_size: 13,
					condition: condition,
					order: this.orderType
				},
				success: res => {
					console.log("res==========================",res)
					let goods = res.data;
					this.$forceUpdate();
					this.searchIndex = true;
					this.priceIndex = true;
					this.pageCount = goods.page_count;
					if (this.pageCount == 0) {
						this.status = 'nomore';
						this.isEmpty = true;
					} else {
						this.status = this.goodsPageIndex < this.pageCount ? 'more' : 'nomore';
					
						this.isEmpty = false;
						if (goods.data.length > 0) {
							this.goodsList = this.goodsList.concat(goods.data);
							for (let i = 0; i < this.goodsList.length; i++) {
								var dates = this.goodsList[i].production_date
								var now = new Date(dates*1000);
								var year = now.getFullYear();
								var month = now.getMonth() + 1;
								if (month < 10) {
									month = '0' + month
									}
								var date = now.getDate();
								if (date < 10) {
									date = '0' + date
									}
								// console.log( year + "-" + month + "-" + date)
								this.goodsList[i].production_date = year + "-" + month + "-" + date
							}
							this.goodsPageIndex++;
						}
					}
					
					// this.$refs.loadingCover.hide();
					
					
					
					
					
					// if(res.data.code == -99999)
					// {
					// 	this.isshow = false
					// 	console.log("未登录",this.isshow)
					// }else if(res.code == 0){
					// 	this.isshow = true
					// 	console.log("登录",this.isshow)
						
					// 	let goods = res.data;
					// 	this.$forceUpdate();
					// 	this.searchIndex = true;
					// 	this.priceIndex = true;
					// 	this.pageCount = goods.page_count;
					// 	if (this.pageCount == 0) {
					// 		this.status = 'nomore';
					// 		this.isEmpty = true;
					// 	} else {
					// 		this.status = this.goodsPageIndex < this.pageCount ? 'more' : 'nomore';
						
					// 		this.isEmpty = false;
					// 		if (goods.data.length > 0) {
					// 			this.goodsList = this.goodsList.concat(goods.data);
					// 			this.goodsPageIndex++;
					// 		}
					// 	}
						
					// 	this.$refs.loadingCover.hide();
					// }
						
					
				
				}
			});
		},
		
		

		/**
		 * 侧边导航栏的点击事件
		 */
		sideNavClick(id, index) {
			console.log("index==================",index)
			// 防止重复点击
			// if (index == this.sideClickIndex) return;
			this.sideClickIndex = index;
			console.log('444444',this.sideClickIndex)
			// 初始化加载状态
			this.status = 'loading';
			// 初始化页数
			this.goodsPageIndex = 1;
			//初始化存储商品的数组
			this.goodsList = [];
			//初始化价格箭头的颜色
			
			this.priceIdent = 0;
			
			this.categoryTwoIdent = index;
			
			//初始化搜索关键词
			this.goodsSearchText = '';

			this.TwoCategoryList = this.categoryList[index].child_list;

			this.sideIdent = index;
			uni.setStorageSync('sideIdentId',this.sideIdent)
			this.category_id = id;
			uni.setStorageSync('categoryId',this.category_id)
			this.getGoodsInfo();
		},
		/**
		 * 综合排序
		 */
		comprehensiveSorting() {
			if (this.conditionIdent == 0) return;
			this.priceIdent = 0;
			this.conditionIdent = 0;
			this.getGoodsInfo('refresh');
		},
		/**
		 * 销量
		 */
		salesVolume() {
			if (this.conditionIdent == 2) return;
			this.priceIdent = 0;
			this.conditionIdent = 2;
			this.orderType = 'ng.sales desc';
			this.getGoodsInfo('refresh');
		},
		/**
		 * 价格
		 */
		price() {
			if (!this.priceIndex) return;
			this.priceIndex = false;
			this.conditionIdent = 1;
			if (this.priceIdent == 2 || this.priceIdent == 0) {
				this.priceIdent = 1;
				this.orderType = 'ng.promotion_price desc';
			} else if (this.priceIdent == 1) {
				this.priceIdent = 2;
				this.orderType = 'ng.promotion_price asc';
			}

			this.getGoodsInfo('refresh');
		},
		/**
		 * 关键词搜索
		 */
		search() {
			if (!this.searchIndex) return;
			this.searchIndex = false;

			this.priceIdent = 0;
			this.goodsSearchText = this.searchText;
			this.getGoodsInfo('refresh');
		}
	}
};
